'use client'

import React, { useState, useEffect } from "react";
import {
    Card,
    CardBody,
    CardHeader,
    Button,
    Spinner,
    Divider,
    Tooltip,
    useDisclosure
} from "@nextui-org/react";
import { BiHistory, BiCheck } from "react-icons/bi";
import ToastUtil from "@/app/utils/toastUtil";
import axios from "axios";
import cookie from "react-cookies";
import { Token } from "@/app/constants/authTokenConstants";
import { format } from "date-fns";

// 创建axios实例
const apiClient = axios.create({
    baseURL: '/',
    timeout: 30000
});

// 添加请求拦截器
apiClient.interceptors.request.use(config => {
    const token = cookie.load(Token);
    if (config && config.headers && token) {
        if (token.startsWith('Bearer ')) {
            config.headers['Authorization'] = token;
        } else {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 历史版本面板属性接口
interface HistoryVersionPanelProps {
    noteId?: number;    // 笔记ID
    onApplyContent?: (content: string) => void; // 应用版本内容的回调
}

// 历史版本接口
interface HistoryVersion {
    version: number;
    createdAt?: string;
    updatedAt?: string;
}

// 笔记内容接口
interface NoteVersionDetail {
    id?: number;
    title?: string;
    content?: string;
    icon?: string;
    emoji?: string;
    version?: number;
    tags?: any[];
    createdAt?: string;
    updatedAt?: string;
}

/**
 * 历史版本管理面板组件
 */
export default function HistoryVersionPanel({
    noteId,
    onApplyContent
}: HistoryVersionPanelProps) {
    // 状态管理
    const [loading, setLoading] = useState<boolean>(false);
    const [loadingDetail, setLoadingDetail] = useState<boolean>(false);
    const [versions, setVersions] = useState<number[]>([]);
    const [selectedVersion, setSelectedVersion] = useState<number | null>(null);
    const [versionDetail, setVersionDetail] = useState<NoteVersionDetail | null>(null);

    // 获取历史版本列表
    const fetchHistoryVersions = async () => {
        if (!noteId) return;

        try {
            setLoading(true);
            const response = await apiClient.get(`/app/api/v1/notes/${noteId}/history`);

            if (response.data.code === 200 && response.data.status === true) {
                setVersions(response.data.data || []);

                // 如果有版本，默认选择第一个
                if (response.data.data && response.data.data.length > 0) {
                    setSelectedVersion(response.data.data[0]);
                    await fetchVersionDetail(response.data.data[0]);
                }
            } else {
                ToastUtil("获取历史版本失败", "❌", "error");
            }
        } catch (error: any) {
            console.error("获取历史版本异常:", error);
            ToastUtil(error.message || "获取历史版本异常", "❌", "error");
        } finally {
            setLoading(false);
        }
    };

    // 获取特定版本详情
    const fetchVersionDetail = async (version: number) => {
        if (!noteId) return;

        try {
            setLoadingDetail(true);
            const response = await apiClient.get(`/app/api/v1/notes/${noteId}/version/${version}`);

            if (response.data.code === 200 && response.data.status === true) {
                setVersionDetail(response.data.data || null);
            } else {
                ToastUtil("获取版本详情失败", "❌", "error");
            }
        } catch (error: any) {
            console.error("获取版本详情异常:", error);
            ToastUtil(error.message || "获取版本详情异常", "❌", "error");
        } finally {
            setLoadingDetail(false);
        }
    };

    // 初始加载
    useEffect(() => {
        if (noteId) {
            fetchHistoryVersions();
        }
    }, [noteId]);

    // 处理版本选择
    const handleSelectVersion = async (version: number) => {
        setSelectedVersion(version);
        await fetchVersionDetail(version);
    };

    // 应用历史版本内容 - 简化，直接应用
    const handleApplyContent = () => {
        if (versionDetail?.content && onApplyContent) {
            onApplyContent(versionDetail.content);
            ToastUtil("历史版本内容已应用", "✅", "success");
        } else {
            ToastUtil("没有可应用的内容", "❌", "error");
        }
    };

    // 格式化版本时间
    const formatVersionTime = (version: number) => {
        // 这里使用版本号作为日期的展示
        // 在实际应用中，可能需要从API获取版本的创建时间
        return `版本 ${version}`;
    };

    return (
        <Card className="w-full">
            <CardHeader className="flex justify-between items-center">
                <div className="flex items-center">
                    <BiHistory className="text-primary mr-2 text-xl" />
                    <h3 className="text-lg font-medium">历史版本</h3>
                </div>
            </CardHeader>

            <Divider />

            <CardBody className="gap-4 max-h-[70vh] overflow-y-auto">
                {/* 加载状态 */}
                {loading && (
                    <div className="flex flex-col items-center justify-center py-8">
                        <Spinner color="primary" />
                        <p className="mt-2 text-sm text-gray-500">加载历史版本中...</p>
                    </div>
                )}

                {/* 无历史版本 */}
                {!loading && versions.length === 0 && (
                    <div className="py-8 text-center text-gray-500">
                        <p>暂无历史版本</p>
                    </div>
                )}

                {/* 版本列表 */}
                {!loading && versions.length > 0 && (
                    <div className="flex flex-col gap-4">
                        <div className="flex flex-wrap gap-2">
                            {versions.map((version) => (
                                <Button
                                    key={version}
                                    size="sm"
                                    variant={selectedVersion === version ? "solid" : "flat"}
                                    color="primary"
                                    onClick={() => handleSelectVersion(version)}
                                    startContent={selectedVersion === version ? <BiCheck /> : null}
                                >
                                    {formatVersionTime(version)}
                                </Button>
                            ))}
                        </div>

                        <Divider />

                        {/* 版本详情 */}
                        {loadingDetail ? (
                            <div className="flex justify-center py-4">
                                <Spinner size="sm" />
                            </div>
                        ) : (
                            <>
                                {versionDetail && (
                                    <div className="space-y-4">
                                        {/* 版本基本信息 */}
                                        <div className="flex justify-between items-center">
                                            <div>
                                                <p className="text-sm text-gray-500">版本 {versionDetail.version}</p>
                                                {versionDetail.updatedAt && (
                                                    <p className="text-xs text-gray-400">
                                                        更新于: {versionDetail.updatedAt.substring(0, 10)}
                                                    </p>
                                                )}
                                            </div>
                                            {onApplyContent && (
                                                <Tooltip content="只应用内容，将覆盖当前编辑器内容">
                                                    <Button
                                                        size="sm"
                                                        color="primary"
                                                        onClick={handleApplyContent}
                                                    >
                                                        应用此版本内容
                                                    </Button>
                                                </Tooltip>
                                            )}
                                        </div>

                                        {/* 版本标题 */}
                                        {versionDetail.title && (
                                            <div>
                                                <h5 className="text-sm font-medium mb-1">标题</h5>
                                                <div className="p-2 bg-gray-100 dark:bg-gray-800 rounded">
                                                    {versionDetail.title}
                                                </div>
                                            </div>
                                        )}

                                        {/* 版本内容 */}
                                        {versionDetail.content && (
                                            <div>
                                                <h5 className="text-sm font-medium mb-1">内容</h5>
                                                <div className="p-2 bg-gray-100 dark:bg-gray-800 rounded h-[300px] overflow-auto">
                                                    <pre className="whitespace-pre-wrap font-sans text-sm">{versionDetail.content}</pre>
                                                </div>
                                            </div>
                                        )}

                                        {/* 标签 */}
                                        {versionDetail.tags && versionDetail.tags.length > 0 && (
                                            <div>
                                                <h5 className="text-sm font-medium mb-1">标签</h5>
                                                <div className="flex flex-wrap gap-1">
                                                    {versionDetail.tags.map((tag: any) => (
                                                        <span
                                                            key={tag.id}
                                                            className="px-2 py-1 bg-primary-100 text-primary rounded-full text-xs"
                                                        >
                                                            {tag.name}
                                                        </span>
                                                    ))}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                )}
            </CardBody>
        </Card>
    );
} 